<template>
  <div class="app-container">
    <div class="Header">
      <edit-form ref="filterContainer" v-show="showSearch" :editFormMap="filterMap" :editFormData="queryParams" @getFormOptionListMap="getFormOptionListMap">
        <template slot="buttonGroup">
          <el-col :span="4">
            <el-form-item class="buttonGroup">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </template>
      </edit-form>
      <div class="handleButtonGroup">
        <div class="button-container">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" v-hasPermi="['label:addOption:addZero']" @click="zeroVisible = true">
            新增0级标签
          </el-button>
          <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
        </div>
      </div>
    </div>
    <table-list
      ref="tableListContainer"
      v-if="refreshTable"
      row-key="rowKey"
      treechildName="childData"
      :isTree="true"
      :tree-props="{ children: 'childData' }"
      :default-expand-all="isExpandAll"
      :tableListMap="tableMap"
      :request="{
        apiKey: 'labelAddOptionList',
        params: queryParams,
        method: 'get',
      }"
      @selection-change="handleSelectionChange"
      @changeTableListAction="
        (TableList) => {
          list = TableList;
        }
      "
    >
      <template slot="hasHandle">
        <el-table-column label="操作" :align="'center'" width="220">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.level === 0"
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleOneLabel(scope.row)"
              v-hasPermi="['label:addOption:addOne']"
            >
              添加1级标签
            </el-button>
            <el-button
              v-if="scope.row.level === 1"
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleTwoLabel(scope.row)"
              v-hasPermi="['label:addOption:addTwo']"
            >
              添加2级标签
            </el-button>
            <el-button
              v-if="scope.row.level !== 0"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['label:addOption:edit']"
            >
              修改
            </el-button>
            <el-button
              v-if="scope.row.level !== 0"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['label:addOption:remove']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </template>
    </table-list>
    <!-- 添加0级标签 -->
    <el-dialog :title="title" :visible.sync="zeroVisible" width="600px" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
      <edit-form
        :inline="true"
        ref="zeroLabelFormContainer"
        :editFormMap="labelFormMap"
        :editFormData.sync="zeroLabelForm"
        :editFormRule="zeroLabelFormRule"
        style="margin-right: 10px"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="zeroVisible = false">取 消</el-button>
        <el-button type="primary" @click="addZeroLabel">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加/修改1、2级标签 -->
    <el-dialog
      :title="labelTitle"
      :visible.sync="labelVisible"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
    >
      <edit-form
        :inline="true"
        ref="editFormContainer"
        :editFormMap="curLevel === 1 ? basicOneFormMap : basicTwoFormMap"
        :editFormData.sync="basicForm"
        :editFormRule="basicFormRule"
        style="margin-right: 10px"
        @getFormOptionListMap="(optionMap) => (optionListMap = optionMap)"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="labelVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as api from '@/api/label/addOption';
import * as addApi from '@/api/label/add';
import { getDataSource } from '@/static/js/dataSource';
import cloneDeep from 'lodash/cloneDeep';
export default {
  name: 'AddOption',
  computed: {
    filterMap() {
      return getDataSource('editForm', 'addFilterMap');
    },
    tableMap() {
      return getDataSource('tableColumn', 'addOptionTableMap');
    },
    basicOneFormMap() {
      let basicOneFormMap = cloneDeep(getDataSource('editForm', 'addOptionFormMap'));
      if (this.curLevel === 1) {
        basicOneFormMap = basicOneFormMap.filter((item) => item.prop !== 'twoLabelId');
      }
      basicOneFormMap.map((item) => {
        if (item.prop === 'zeroLabelId') {
          Object.assign(item, { disabled: true });
        }
      });
      return basicOneFormMap;
    },
    basicTwoFormMap() {
      let basicTwoFormMap = cloneDeep(getDataSource('editForm', 'addOptionFormMap'));
      if (this.curMode === 'edit') {
        basicTwoFormMap = basicTwoFormMap.filter((item) => item.prop === 'twoLabelId');
      }
      basicTwoFormMap.map((item) => {
        if (['zeroLabelId', 'oneLabelId'].includes(item.prop)) {
          Object.assign(item, { disabled: true });
        }
      });
      return basicTwoFormMap;
    },
    basicFormRule() {
      return getDataSource('editRule', 'addOptionFormRule');
    },
    labelFormMap() {
      const addFormMap = cloneDeep(getDataSource('editForm', 'addLabelFormMap'));
      addFormMap.some((item) => {
        if (item.prop === 'level') {
          Object.assign(item, { disabled: true });
          this.$set(this.zeroLabelForm, 'level', 0);
          return true;
        }
      });
      return addFormMap;
    },
    zeroLabelFormRule() {
      return getDataSource('editRule', 'addFormRule');
    },
  },
  data() {
    return {
      // 当前页面
      refreshTable: true,
      isExpandAll: true,
      pageTitle: '得分标签配置',
      optionListMap: {},
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {},
      // 表单参数
      basicForm: {},

      // 0级标签
      zeroVisible: false,
      zeroLabelForm: {},

      // 添加/修改1、2级标签
      labelTitle: '',
      labelVisible: false,
      labelForm: {},
      curLevel: 0,
      curMode: 'add',
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
        this.getList();
      });
    },
    /** 查询列表 */
    getList() {
      this.$nextTick(() => {
        this.$refs.tableListContainer.init();
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.basicForm = this.$options.data().basicForm;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      const tableListContainer = this.$refs.tableListContainer;
      tableListContainer.pagination = tableListContainer.$options.data().pagination;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      const filterContainer = this.$refs.filterContainer;
      filterContainer.resetForm('editFormData');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.curLevel = row.level;
      const ids = row ? row.id : this.ids.join(',');
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(() => {
          const curLevelMap = {
            1: api.delOneLabelOption,
            2: api.delTwoLabelOption,
          };
          return curLevelMap[this.curLevel](ids);
        })
        .then(() => {
          this.getList();
          this.$message.success('删除成功');
        })
        .catch(() => {});
    },
    /** 新增0级标签 */
    addZeroLabel() {
      const zeroLabelFormContainer = this.$refs.zeroLabelFormContainer;
      zeroLabelFormContainer.$refs.editFormData.validate((basicValid) => {
        if (basicValid) {
          const params = cloneDeep({ ...this.zeroLabelForm });
          addApi.addItem(params).then(() => {
            this.$message.success('新增成功');
            this.zeroVisible = false;
            this.getList();
          });
        }
      });
    },
    handleUpdate(row) {
      const paramsMap = {
        1: { zeroLabelId: row.parentId, oneLabelId: row.id, id: row.id },
        2: { oneLabelId: row.parentId, twoLabelId: row.id, id: row.id },
      };
      row.level === 1 ? this.handleOneLabel(row, paramsMap[row.level]) : this.handleTwoLabel(row, paramsMap[row.level]);
    },
    /** 新增/修改1级标签 */
    handleOneLabel(row, params) {
      this.curMode = params ? 'edit' : 'add';
      this.curLevel = 1;
      this.basicForm = cloneDeep({ zeroLabelId: row.id, ...(params || {}) });
      this.labelTitle = (params ? '修改' : '新增') + '1级标签';
      this.labelVisible = true;
    },
    /** 新增/修改2级标签 */
    handleTwoLabel(row, params) {
      this.curMode = params ? 'edit' : 'add';
      this.curLevel = 2;
      this.basicForm = cloneDeep({ zeroLabelId: row.parentId, oneLabelId: row.id, ...(params || {}) });
      this.labelTitle = (params ? '修改' : '新增') + '2级标签';
      this.labelVisible = true;
    },
    getFormOptionListMap() {},
    /** 提交按钮 */
    submitForm() {
      const editFormContainer = this.$refs.editFormContainer;
      editFormContainer.$refs.editFormData.validate((basicValid) => {
        const curLevelMap = {
          1: api.updateOneLabelOption,
          2: api.updateTwoLabelOption,
        };
        if (basicValid) {
          if (this.basicForm.id) {
            curLevelMap[this.curLevel](this.basicForm).then(() => {
              this.$message.success('修改成功');
              this.labelVisible = false;
              this.getList();
            });
          } else {
            const params = cloneDeep({ ...this.basicForm });
            api.addLabelOption(params).then(() => {
              this.$message.success('新增成功');
              this.labelVisible = false;
              this.getList();
            });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>
